﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace BluEtch.GotPhone.Helpers
{
    /// <summary>
    /// Helps with serializing objects to and from JSON.
    /// </summary>
    public static class Serialization
    {
        public static string Serialize<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                string retVal = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
                return retVal;
            }
        }

        public static T Deserialize<T>(string json)
        {
            T obj = GetInstance<T>();
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                obj = (T)serializer.ReadObject(ms);
                return obj;
            }
        }

        private static T GetInstance<T>()
        {
            //Strings don't have a parameterless constructor
            if (typeof(T) != typeof(String))
            {
                return (T)Activator.CreateInstance(typeof(T));
            }
            else
            {
                return default(T);
            }
        }
    }
}
